package com.sin.j2me.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.sin.j2me.Debug;

public class ThreadGet extends Thread {
	private WhenGetted whengetted = null;
	private String url = null;

	public ThreadGet(WhenGetted wg, String u){
		whengetted = wg;
		url = u;
	}
	public void run(){
		String get = null;
		get = getHttpConnection(url);
		whengetted.getted(get);
	}
	
    private String getHttpConnection(String url){
        HttpConnection c = null;
        InputStream is = null;
        String res = null;
        int rc;

        try {
            c = (HttpConnection)Connector.open(url);
			c.setRequestProperty("connection", "Keep-Alive");
			c.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			c.setRequestProperty("Charsert", "UTF-8");
			c.setRequestMethod(HttpConnection.GET);
			Debug.Error("ST0");
            // rc = c.getResponseCode();
            Debug.Error("ST1");
//            if (rc != HttpConnection.HTTP_OK) {
//                //throw new IOException("HTTP response code: " + rc);
//                return null;
//            }
            Debug.Error("ST2");
            is = c.openInputStream();
            Debug.Error("ST3");
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            Debug.Error("ST4");
            int ch;
            StringBuffer sb = new StringBuffer();
            while ((ch = isr.read()) != -1) {
                sb.append((char)ch);
            }
            Debug.Error("ST5");
            res = sb.toString();
        }
        catch (Exception e) {
            Debug.Error(e);
        }
        return res;
    }
}
